package com.niit.mobileDevide.operatesystem;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class OperateSystemMapper extends Mapper<LongWritable, Text, Text, Text> {

    // 定义各字段的索引位置
    private static final int AGE_INDEX = 8; // 年龄
    private static final int OPERATING_SYSTEM_INDEX = 2; // 操作系统

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        // 打印输入行，方便调试
        System.out.println("Processing line: " + value);

        // 忽略标题行（可选）
        if (key.get() == 0) return;

        String[] columns = value.toString().split(",");
        if (columns.length < 9) { // 确保至少有9个字段（考虑到AGE_INDEX是8）
            System.err.println("Skipping line due to insufficient fields: " + value);
            return;
        }

        try {
            // 解析年龄和操作系统
            String ageStr = columns[AGE_INDEX].trim();
            int age = Integer.parseInt(ageStr);

            String operatingSystem = columns[OPERATING_SYSTEM_INDEX].trim();

            // 只处理操作系统为1或2的记录
            if ("1".equals(operatingSystem) || "2".equals(operatingSystem)) {
                // 根据年龄范围和操作系统类型设置不同的键
                String osKey;
                if (age > 30) {
                    osKey = "OS" + operatingSystem + "_Above30";
                } else {
                    osKey = "OS" + operatingSystem + "_Below30";
                }

                // 使用操作系统特定的键作为键，值可以是任意非空字符串（例如"1"）
                context.write(new Text(osKey), new Text("1"));
            } else {
                System.err.println("Invalid operating system: " + operatingSystem + ". Skipping line.");
            }

        } catch (NumberFormatException e) {
            // 跳过格式错误的行，并打印错误信息
            System.err.println("Error parsing line: " + value + ". Error: " + e.getMessage());
        }
    }
}